package org.sanqi.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.sanqi.demo.entity.User;
import org.sanqi.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: JenSen
 * @Date: 2024/5/22 14:24
 * @Description: UserServiceImpl
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> {


    @Autowired
    private CacheManager cacheManager;
    @CachePut(value = "saveuser",key = "#user.sno")
    public User saveUser(User user){
        if (baseMapper.insert(user) > 0){
            return baseMapper.selectOne(new QueryWrapper<User>().eq("sno",user.getSno()));
        }
        return  null;
    }


//    @Cacheable(value = "userlist")
    public List<User> getUserList(){
        return baseMapper.selectList(null);
    }

    @CacheEvict(value = "userlist",allEntries = true)
    public void deleteAll(){
        System.out.println("清空所有缓存...");
    }

    /**
     * 获取本地缓存管理器中的缓存
     */
    public void getConcurrentHashMapCache(){
        //缓存器集合
        System.out.println("缓存器集合:" + cacheManager.getCacheNames());
        for (String cacheName : cacheManager.getCacheNames()) {
            //每个缓存器中的key-value
            System.out.println(cacheName + ":" +cacheManager.getCache(cacheName).getNativeCache());
        }
        System.out.println("类型:" + cacheManager.getClass().getName());
    }

    /**
     * 使用@CachePut注解
     */
//    @CachePut(value = "userlist",key = "'userlist'")
    public List<User> updateUser(User user){
        if (baseMapper.update(user,new QueryWrapper<User>().eq("sno",user.getSno())) > 0){
            return baseMapper.selectList(null);
        }
        return  null;
    }
}
